<!-- 单位编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="800"
    :model-value="modelValue"
    title="商品移库"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="货主" prop="supplier_id">
            <el-select v-model="form.supplier_id" placeholder="请选择货主" clearable @change="supplierChange">
              <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库" prop="warehouse_id">
            <el-select v-model="form.warehouse_id" :disabled="!form.supplier_id" placeholder="请选择仓库" clearable>
              <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="商品" label-position="top">
        <template #label>
          <div class="flex-a ">
            <div class="">商品</div>
            <div class="flex-1 ml-12px mr-30px">
              <el-button type="primary" plain @click="showProduct = true">添加商品</el-button>
            </div>
            <div class="flex-a">
              <div>新库位：</div>
              <el-cascader
                v-model="locationId"
                :options="locationTree"
                filterable
                clearable
                placeholder="请选择库位"
                :show-all-levels="false"
                placement="left"
                :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
              />
              <el-button type="primary" :disabled="!locationId" plain class="ml-10px" @click="batchLocation">批量设置</el-button>
            </div>
          </div>
        </template>
        <el-table ref="tableRef" height="45vh" :data="form.product" size="small">
          <el-table-column type="index" label="序" width="40" align="left" />
          <el-table-column prop="product_name" label="商品名称" width="" />
          <el-table-column prop="product_code" label="商品编码" align="center" width="120" />
          <el-table-column prop="location_name" label="原库位" align="center" width="160" />
          <el-table-column prop="new_location_id" label="新库位" align="center">
            <template #default="{ $index, row }">
              <div class="flex-c">
                <el-form-item
                  :label-width="0"
                  :prop="`product[${$index}].new_location_id`"
                  required
                  :rules="ruleLoc"
                  class="mb-0!"
                >
                  <el-cascader
                    v-model="form.product[$index].new_location_id"
                    :options="locationTree"
                    size="small"
                    filterable
                    clearable
                    placeholder="请选择库位"
                    :show-all-levels="false"
                    placement="left"
                    :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false, disabled: v => v.id === row.location_id }"
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
    <SelectProduct
      v-model="showProduct"
      :selecteds="form.product"
      :where="{ warehouse_id: form.warehouse_id, is_location: 1 }"
      :showPirce="false"
      :editNum="false"
      @done="selectProduct"
    />
  </ele-modal>
</template>

<script setup>
import { listBanWarehouse, listWlList } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'
import { toTree } from 'ele-admin-plus/es'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  supplierList: Array,
})

const emit = defineEmits(['done', 'update:modelValue'])

const locationId = ref()

const showProduct = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)
const tableRef = ref(null)

const ruleLoc = [{ required: true, trigger: ['change', 'blur'] }]

const rules = {
  supplier_id: {
    required: true,
    message: '请选择货主',
    trigger: 'change',
  },
  warehouse_id: {
    required: true,
    message: '请选择仓库',
    trigger: 'change',
  },
  product: {
    required: true,
    message: '请选择商品',
    trigger: 'change',
    type: 'array',
  },
}

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  product: [],
  warehouse_id: '',
  supplier_id: '',
})

const locationTree = ref([])

function getLocationTree() {
  listWlList(form.warehouse_id).then((res) => {
    locationTree.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
  })
}

function selectProduct(data) {
  data.forEach((v) => {
    const loac = v.location || []
    v.location_id = loac.map(v => v.id)
    v.location_name = loac.map(v => v.name).join(',')
  })
  form.product.push(...data)

  // setTimeout(() => {
  //   tableRef.value.doLayout()
  // }, 200)
}

function batchLocation() {
  form.product.forEach((v) => {
    v.new_location_id = locationId.value
  })
  formRef.value?.clearValidate?.()
}
const warehouseList = ref([])

async function supplierChange(value) {
  if (value) {
    const res = await listBanWarehouse(value)
    warehouseList.value = res.data
  }
  else {
    warehouseList.value = []
  }
  if (form.warehouse_id && !warehouseList.value.some(v => v.id === form.warehouse_id)) {
    form.warehouse_id = ''
  }
}

watch(() => form.warehouse_id, (newVal) => {
  if (newVal) {
    getLocationTree()
  }
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    utils.post('/stockMove/edit', {
      warehouse_id: form.warehouse_id,
      product: form.product.map(v => ({
        product_id: v.product_id,
        old_location_id: v.location_id.length > 1 ? 0 : v.location_id[0],
        new_location_id: v.new_location_id,
      })),
    })
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (!modelValue) {
      resetFields()
      formRef.value?.clearValidate?.()
      locationId.value = 0
    }
  },
)
</script>
